package com.may.wlrj.services;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.context.request.async.DeferredResult;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.machinezoo.sourceafis.FingerprintImage;
import com.machinezoo.sourceafis.FingerprintTemplate;
import com.may.wlrj.dao.LockDAO;
import com.may.wlrj.dao.LogDAO;
import com.may.wlrj.dao.RoleDAO;
import com.may.wlrj.dao.UserDAO;
import com.may.wlrj.dao.UserRoleDAO;
import com.may.wlrj.entity.FingerEntity;
import com.may.wlrj.entity.OrganizationEntity;
import com.may.wlrj.entity.RoleEntity;
import com.may.wlrj.entity.UserEntity;
import com.may.wlrj.entity.UserLogEntity;
import com.may.wlrj.entity.UserOperLogEntity;
import com.may.wlrj.entity.UserRoleEntity;
import com.may.wlrj.entity.UserRoleUnionOrg;
import com.may.wlrj.finger.ZZFingerUtil;
import com.may.wlrj.sourceafis.AFISUtil;
import com.may.wlrj.util.XinLongUtil;

@Service
@Transactional
public class UserService {
	private Logger log = Logger.getLogger(UserService.class);
	private UserDAO userDao;
	private final String defaultpsw = "MTIzNDU2Nzg=";
	private int userlogtry = 0;
    @Autowired
    public void setUserDao(UserDAO userDao){
        this.userDao =userDao;
    }
    
    private RoleDAO roleDao;
	@Autowired
	public void setRoleDAO(RoleDAO roleDao) {
		this.roleDao = roleDao;
	}
	
	private UserRoleDAO userroleDao;
	@Autowired
	public void setUserRoleDAO(UserRoleDAO userroleDao) {
		this.userroleDao = userroleDao;
	}
	
	private LogDAO userlogDao;
	@Autowired
	public void setUserOperLogDAO(LogDAO userlogDao) {
		this.userlogDao = userlogDao;
	}
	
	private LockDAO lockDao;
	@Autowired
	public void setLockDao(LockDAO lockDao) {
		this.lockDao = lockDao;
	}

	private int insertUserOperLog(String remoteaddr, String username,String createuser,String name,String ckuser,String org_id){
		UserOperLogEntity useroperlog = new UserOperLogEntity();
    	useroperlog.setId(UUID.randomUUID().toString().replace("-", ""));
    	Date date = new Date();
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	useroperlog.setCreatetime(dateFormat.format(date));
    	useroperlog.setRemoteaddr(remoteaddr);
    	useroperlog.setRname(name);
    	useroperlog.setUser_create(createuser);
    	useroperlog.setUsername(username);
    	useroperlog.setOrg_id(org_id);
    	if(!ckuser.equals("")){
    		useroperlog.setUser_check(ckuser);
    	}    	
    	if(userlogDao.insertLog(useroperlog) == 0){    		
    		return 0;
    	}
    	return 1;
	}	
	
    public String userAuth(String jsonstr,HttpServletRequest request,HttpSession session) throws JsonProcessingException{
    	ObjectMapper mapper = new ObjectMapper();  
		ObjectNode res = mapper.createObjectNode();
		String remoteaddr = XinLongUtil.getRemoteAddr(request);
		Date date = new Date();
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setRname("用户登录");
		XinLongUtil.xinLongUtil.printlog(log,jsonstr);
		/*if(XinLongUtil.xinLongUtil.getLicensedays() < 1){
			res.put("status", "2");
			res.put("desc", "软件已到期,请重新购买证书!");	  
            return mapper.writeValueAsString(res);
		}*/
		try{
			com.fasterxml.jackson.databind.JsonNode rootNode = mapper.readTree(jsonstr);		
			String username =rootNode.get("username").asText();
			String password=rootNode.get("password").asText();
			 if(username!=null){
				ulog.setCreateusername(username);
	        	UserEntity uentity = hasMatchCount(username);
	        	if(uentity == null){
	        		res.put("status", "2");
	    			res.put("desc", "用户名错误!");	    			
	                //重定向到主页面的跳转方法
	                return mapper.writeValueAsString(res);
	        	}
	        	if(uentity.getStatus() == 1){
	        		//该账户已被锁定
	        		res.put("status", "2");
	    			res.put("desc", "账号已被锁定,需管理员解锁才能继续使用!");
	    			ulog.setUserid(uentity.getId());
	    			ulog.setDescriptor("账号已被锁定");
	    			ulog.setProceed("验证失败");
	    			XinLongUtil.saveUserLog(ulog);
	                //重定向到主页面的跳转方法
	                return mapper.writeValueAsString(res);
	        	}else if(uentity.getStatus() == 2){
	        		res.put("status", "2");
	    			res.put("desc", "账号未激活,需管理员激活才能继续使用!");
	                //重定向到主页面的跳转方法
	    			ulog.setUserid(uentity.getId());
	    			ulog.setDescriptor("账号未激活");
	    			ulog.setProceed("验证失败");
	    			XinLongUtil.saveUserLog(ulog);
	                return mapper.writeValueAsString(res);
	        	}
	        	if(uentity != null && password!=null && password.equals(uentity.getPassword())){
	        		XinLongUtil.xinLongUtil.printlog(log,"验证成功!");
	        		session.setAttribute("USER_SESSION",uentity);
	        		uentity.setLastlogintime(dateFormat.format(date));
	        		//登录成功,累计失败次数清0
	        		uentity.setTryloginno(0);
	        		userDao.updateuser(uentity);
	        		res.put("status", "1");
	    			res.put("desc", "验证成功!");	    			
	    			ulog.setUserid(uentity.getId());
	    			ulog.setProceed("登录成功");
	    			XinLongUtil.saveUserLog(ulog);
	    			
	                //重定向到主页面的跳转方法
	                return mapper.writeValueAsString(res);
	        	}else{
	        		userlogtry = XinLongUtil.getLoginTryNo();
	        		XinLongUtil.xinLongUtil.printlog(log,"--------------userlogtry=" + userlogtry + "----" + uentity.getTryloginno());
	        		if(uentity.getTryloginno() > userlogtry - 2){
	        			//登录次数超限,锁定该用户
	        			uentity.setStatus(1);        			
	        			userDao.updateuser(uentity);
	        			res.put("status", "2");
		    			res.put("desc", "账号已被锁定,需管理员解锁才能继续使用!");
		    			ulog.setUserid(uentity.getId());
		    			ulog.setDescriptor("密码错误次数超限,账号被锁定");
		    			ulog.setProceed("验证失败");
		    			XinLongUtil.saveUserLog(ulog);
		                //重定向到主页面的跳转方法
		                return mapper.writeValueAsString(res);
	        		}else{
	        			updatetryno(uentity); 
	        			res.put("status", "2");
		    			res.put("desc", "密码错误,你还有"+ (userlogtry - uentity.getTryloginno() - 1) + "次重试机会!");
		                return mapper.writeValueAsString(res);
	        		}
	        		       		
	        	}
	        }
    	}catch(EmptyResultDataAccessException er){           	
    		res.put("status", "0");
			res.put("desc", "找不到该用户!");
			log.error(er.getMessage());
    	}catch(Exception e){
    		res.put("status", "0");
			res.put("desc", "未知错误!");
			log.error(e.getMessage());
    	}
    	
		return mapper.writeValueAsString(res);
    }
    
    public String getUserinitCore(HttpSession session) throws JsonProcessingException{
    	UserEntity uentity = (UserEntity)session.getAttribute("USER_SESSION");
    	ObjectMapper mapper = new ObjectMapper(); 
    	ObjectNode res = mapper.createObjectNode();
    	try{
    		uentity = userDao.findByUserName(uentity.getUsername());
    		res.put("status", "1");
    		res.put("username", uentity.getRolename() + "-" + uentity.getUsername());
    		if(XinLongUtil.isNeedChangePsw() == 1){
    			res.put("needupdatepsw", uentity.getNeedpwdchange());
    		}else{
    			res.put("needupdatepsw", 0);
    		}    		
    		res.put("systitle", XinLongUtil.getSysTitle());
    		/*if(XinLongUtil.xinLongUtil.getLicensedays() < 7){
				res.put("licensedays", "软件即将到期,剩余" + XinLongUtil.xinLongUtil.getLicensedays() + "天!");
			}
			res.put("licensedate", XinLongUtil.xinLongUtil.getLicensedate() );
			*/
    		res.put("istip", XinLongUtil.isMissionTip(uentity.getUsername()));
    		res.put("roleid", "");
			res.put("desc", "成功!");
    	}catch(EmptyResultDataAccessException er){
    		res.put("status", "2");
			res.put("desc", "找不到该用户!");
			log.error(er.getMessage());
    	}catch(Exception e){
    		res.put("status", "0");
			res.put("desc", "未知异常!");
			log.error(e.getMessage());
    	}
    	
    	return mapper.writeValueAsString(res);  
    }
    
    public UserEntity hasMatchCount(String userName) throws EmptyResultDataAccessException{
    	try{    		
    		return userDao.findByUserName(userName);
    	}catch(EmptyResultDataAccessException er){
    		return null;
    	}catch(Exception e){
    		log.error(e.getMessage());
    		return null;//其它异常
    	}
    }
    
    public void C_UserDelete(DeferredResult<String> deferredResult,String jsonstr,HttpServletRequest request ,HttpSession session) throws JsonProcessingException{
		ObjectMapper mapper = new ObjectMapper();
		ObjectNode resjson = mapper.createObjectNode();  
		String username ="";
		String id="";
		String rname = "";
		String ckname = "";
		XinLongUtil.xinLongUtil.printlog(log,jsonstr);
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	Date date = new Date();
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	String remoteaddr = XinLongUtil.getRemoteAddr(request);
    	UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setRname("用户管理/删除");
		ulog.setCreateusername(sentity.getUsername());
		ulog.setUserid(sentity.getId());
		ulog.setMethod("UserDelete");
    	com.fasterxml.jackson.databind.JsonNode rootNode;
		try {
			rootNode = mapper.readTree(jsonstr);
			username =rootNode.get("username").asText();
			id=rootNode.get("id").asText();
			rname =rootNode.get("rname").asText();
			ckname =rootNode.get("ckname").asText();
		} catch (IOException e) {
			resjson.put("status", "0");
    		resjson.put("desc", "上传数据解析异常!");
    		log.error(e.getMessage());
    		deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}		
		UserEntity user = userDao.findByUserName(username);
		if(user == null) {
			resjson.put("status", "0");
			resjson.put("desc", "找不到该用户信息!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}
		//人员变更机构,名下锁具和钥匙需先移交
		if(lockDao.findLocksByUser(username).size() > 0) {
			resjson.put("status", "0");
			resjson.put("desc", "[" + user.getRealName() + "]名下还有锁具,请先移交!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}
		//判断名下是否有钥匙
		if(lockDao.findKeysByUserCount("", username) > 0) {
			resjson.put("status", "0");
			resjson.put("desc", "[" + user.getRealName() + "]名下还有钥匙,请先移交!");
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}
		ulog.setCreate_check_userid(ckname);
		ulog.setOrgid(sentity.getOrg_id());
    	if(insertUserOperLog(remoteaddr,username,sentity.getUsername(),rname,ckname,sentity.getOrg_id()) == 0){
    		resjson.put("status", "0");
    		resjson.put("desc", "添加用户日志失败!");
    		deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
    	}
    	if(userDao.delete(username) == 0){
    		resjson.put("status", "0");
    		resjson.put("desc", "删除用户失败!");
    		TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			ulog.setDescriptor("删除用户失败");
			ulog.setProceed("删除用户失败");
			XinLongUtil.saveUserLog(ulog);
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
    	}
    	if(UserDelRelate(id) == 0){
    		resjson.put("status", "0");
    		resjson.put("desc", "删除用户关联信息失败!");
    		TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			ulog.setDescriptor("删除用户关联信息失败");
			ulog.setProceed("删除用户关联信息失败");
			XinLongUtil.saveUserLog(ulog);
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
    	}
		ulog.setDescriptor(user.getUsername() + ":" + user.getRealName() + "被删除");
		ulog.setProceed("操作成功");
		XinLongUtil.saveUserLog(ulog);
    	resjson.put("status", "1");
		resjson.put("desc", "成功!");
		deferredResult.setResult(mapper.writeValueAsString(resjson));
		return;
    }
    
    //删除用户时,判断是否有关联数据,并删除冗余数据
    private int UserDelRelate(String userid){
    	//删除关联的角色信息
    	XinLongUtil.xinLongUtil.printlog(log,"-----------userid=" + userid);
    	if(userroleDao.deleteByuserid(userid) == -1){
    		return 0;
    	}
    	
    	return 1;
    }
    
    /*public List<UserRoleUnionOrg> getSubOrgUserList(String orgid){
    	List<UserRoleUnionOrg> userlist = new ArrayList<>();
    	List<String> suborgs = userDao.findSubOrg(orgid);
    	if(suborgs != null){
    		List<UserRoleUnionOrg> urolist;
    		for(OrganizationEntity org : suborgs){
    			urolist = userDao.findAll(0,0,org.getId());
    			if(urolist != null){
    				try{    		
        	        	if(urolist.size() > 0){
        	        		//赋值角色
        	        		for(UserRoleUnionOrg ur : urolist){
        	        			RoleEntity role = roleDao.findRolenameByUserId(ur.getId());
        	        			if(role != null){
        	        				ur.setRoleid(role.getId());
        	            			ur.setRolename(role.getRolename());
        	        			}        			
        	        		}
        	        	}
        	        	
        	        	
        	    	}catch(Exception e){
        	    		log.error(e.getMessage());
        	    	}
    				urolist.addAll(getSubOrgUserList(org.getId()));
    				userlist.addAll(urolist);
    			}    	    	
    		}
    		
    	}
    	return userlist;
    }*/
    
    public String getUserlist(String jsonstr,HttpServletRequest request ,HttpSession session) throws IOException{
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	ObjectMapper mapper = new ObjectMapper();  
    	ObjectNode resjson = mapper.createObjectNode(); 
    	com.fasterxml.jackson.databind.JsonNode rootNode;	
    	int pageNumber = 0;
    	int pageSize = 0;
    	String orgname = "";
    	String username = "";
    	try {
			rootNode = mapper.readTree(jsonstr);
			pageNumber =rootNode.get("pageNumber").asInt();
			pageSize=rootNode.get("pageSize").asInt();
			orgname = rootNode.get("orgname").asText();
			username = rootNode.get("username").asText();
		} catch (IOException e) {
			resjson.put("status", "0");
    		resjson.put("desc", "上传数据解析异常!");
    		log.error(e.getMessage());
    		return mapper.writeValueAsString(resjson);
		}	
    	List<UserRoleUnionOrg> urolist = null;
    	List<OrganizationEntity> suborgs = null;
    	if(userDao.isRootOrg(sentity.getOrg_id())) {
    		urolist =userDao.findAll(pageNumber,pageSize,orgname,username);
    	}else {
    		suborgs = userDao.findSubOrg(sentity.getOrg_id());
        	
        	if(suborgs != null && suborgs.size() > 0){
        		urolist =userDao.findSubAll(suborgs,pageNumber,pageSize,orgname,username);
        	}
    	}
    	try{    		
        	if(urolist !=null && urolist.size() > 0){
        		//赋值角色
        		for(UserRoleUnionOrg ur : urolist){
        			RoleEntity role = roleDao.findRolenameByUserId(ur.getId());
        			if(role != null){
        				ur.setRoleid(role.getId());
            			ur.setRolename(role.getRolename());
        			}        			
        		}
        	}
    	}catch(Exception e){
    		log.error(e.getMessage());
    	}
    	ArrayNode rootnode = mapper.createArrayNode();
    	if(urolist != null){			
			ObjectNode tjson = null;
			for(UserRoleUnionOrg user : urolist){
				tjson = mapper.createObjectNode();
				tjson.put("id", user.getId());
    			tjson.put("username", user.getUsername());
    			tjson.put("sex", user.getSex());
    			tjson.put("realname", user.getRealname());
    			tjson.put("org_name", user.getOrg_name());
    			tjson.put("phone", user.getPhone());
    			tjson.put("org_id", user.getOrg_id());
    			tjson.put("descriptor", user.getDescriptor());
    			tjson.put("idcard", user.getIdcard());  
    			tjson.put("jobname", user.getJobname());
    			tjson.put("rolename", user.getRolename());
    			tjson.put("status", user.getStatus());  
    			tjson.put("authtype", user.getAuthtype());
    			rootnode.add(tjson);
			}
			resjson.put("status", "1");
			if(userDao.isRootOrg(sentity.getOrg_id())) {
				resjson.put("totalCount", userDao.getUserCount(orgname,username));
			}else {
				resjson.put("totalCount", userDao.getUserCount(suborgs,orgname,username));
			}
	    	
	    	resjson.put("pageSize", pageSize);
	    	resjson.put("datalist", rootnode);
	        return mapper.writeValueAsString(resjson);
    	}else {
    		resjson.put("status", "1");
	    	resjson.put("totalCount", "0");
	    	resjson.put("pageSize", pageSize);
	    	resjson.put("datalist", rootnode);
	        return mapper.writeValueAsString(resjson);
    	}
    	
    }
    
    public String getUserlistbyauth(HttpSession session) throws IOException{
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	ObjectMapper mapper = new ObjectMapper();  
    	/*List<OrganizationEntity> suborgs = userDao.findSubOrg(sentity.getOrg_id());
    	List<UserRoleUnionOrg> urolist = null;
    	if(suborgs != null && suborgs.size() > 0){
    		urolist =userDao.findSubAll(suborgs);
    	}else{
    		urolist = userDao.findAll(sentity.getOrg_id());
    	}*/
    	List<UserRoleUnionOrg> urolist = userDao.findAll(sentity.getOrg_id());
    	ArrayNode rootnode = mapper.createArrayNode();
    	if(urolist.size() > 0){
    		//赋值角色    		
			ObjectNode tjson = null;
    		for(UserRoleUnionOrg ur : urolist){
    			tjson = mapper.createObjectNode();
				tjson.put("id", ur.getId());
    			tjson.put("username", ur.getUsername());
    			tjson.put("orgname", ur.getOrg_name());
    			tjson.put("realname", ur.getRealname());
    			rootnode.add(tjson);
    		}
    	}
        return mapper.writeValueAsString(rootnode);
    }
    
    public void _insertuser(DeferredResult<String> deferredResult,String jsonstr, HttpServletRequest request,HttpSession session) throws JsonProcessingException{  
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	String remoteaddr = XinLongUtil.getRemoteAddr(request);
    	ObjectMapper mapper = new ObjectMapper(); 
    	ObjectNode resjson = mapper.createObjectNode();
    	UserEntity user = new UserEntity();
    	com.fasterxml.jackson.databind.JsonNode rootNode;
    	XinLongUtil.xinLongUtil.printlog(log,jsonstr);
    	String username = "";
    	String phone = "";    	
    	String rname = "";
    	String org_id = "";
    	String jobname = "";
    	String realname = "";
    	String idcard = "";
    	String sex = "";
    	String descriptor = "";
    	String ckname = "";
    	try{
    		rootNode = mapper.readTree(jsonstr);
    		username =rootNode.get("username").asText();
    		phone =rootNode.get("phone").asText();
			rname = rootNode.get("rname").asText();
			org_id =rootNode.get("org_id").asText();
			jobname =rootNode.get("jobname").asText();
			realname =rootNode.get("realname").asText();
			idcard = rootNode.get("idcard").asText();
			sex = rootNode.get("sex").asText();
			descriptor = rootNode.get("descriptor").asText();
			ckname = rootNode.get("ckname").asText();
    	}catch (IOException e1) {
    		resjson.put("status", "2");
    		resjson.put("desc", "解析上传数据异常!");
    		log.error(e1.getMessage());
    		deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}	
    	//权限判断
    	/*resjson = XinLongUtil.OptAuth("",jsonstr, sentity);
		if(!resjson.get("status").asText().equals("1210")){
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}*/
		Date date = new Date();
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setRname("用户管理/添加用户");
		ulog.setCreateusername(sentity.getUsername());
		ulog.setUserid(sentity.getId());
		ulog.setCreate_check_userid(ckname);
		ulog.setOrgid(sentity.getOrg_id());
		ulog.setMethod("insertuser");
		user.setPassword(defaultpsw);
        
		String uId = UUID.randomUUID().toString().replace("-", "");
		user.setId(uId);
		user.setCreatetime(dateFormat.format(date));
		user.setNeedpwdchange(XinLongUtil.xinLongUtil.isNeedChangePsw());
		user.setCreatename(sentity.getUsername());
		user.setTryloginno(0);
		user.setAuthtype(0);
		user.setStatus(2);
		user.setSex(sex);
		user.setUsername(username);
		user.setRealName(realname);
		user.setDescriptor(descriptor);
		user.setIdcard(idcard);
		user.setJobname(jobname);
		user.setOrg_id(org_id);
		user.setPhone(phone);
		
		try{
    		if(userDao.findByUserName(user.getUsername()) != null) {
	    		resjson.put("status", "0");
				resjson.put("desc", "用户名已存在!");
				deferredResult.setResult(mapper.writeValueAsString(resjson));
				return;
    		}
    		if(userDao.saveuser(user) == 0){
    			resjson.put("status", "0");
    			resjson.put("desc", "添加用户失败!");
    			deferredResult.setResult(mapper.writeValueAsString(resjson));
    			return;
    		}
    		XinLongUtil.xinLongUtil.printlog(log,"添加用户操作日志");
    		if(insertUserOperLog(remoteaddr,username,sentity.getUsername(),rname,ckname,sentity.getOrg_id()) == 0){
    			resjson.put("status", "0");
    			resjson.put("desc", "添加日志失败!");
    			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    			deferredResult.setResult(mapper.writeValueAsString(resjson));
    			return;
    		}else{
    			resjson.put("status", "1");
    			resjson.put("desc", "成功!");
    			ulog.setDescriptor(username + "被添加");
    			ulog.setProceed("操作成功");
    			XinLongUtil.saveUserLog(ulog);
    		}
    	}catch(Exception e){
    		resjson.put("status", "2");
			resjson.put("desc", "未知异常!");
			ulog.setDescriptor(e.getMessage());
			ulog.setProceed("操作失败");
			XinLongUtil.saveUserLog(ulog);
			log.error(e.getMessage());
    	}
		deferredResult.setResult(mapper.writeValueAsString(resjson));
		return;
    }
    
    public String updatepsw(String jsonstr, HttpServletRequest request,HttpSession session) throws Exception{
    	UserEntity uentity = (UserEntity)session.getAttribute("USER_SESSION");
    	XinLongUtil.xinLongUtil.printlog(log,jsonstr);
    	ObjectMapper mapper = new ObjectMapper(); 
    	UserEntity userentity;
    	String remoteaddr = XinLongUtil.getRemoteAddr(request);
    	ObjectNode resjson = mapper.createObjectNode();  
    	com.fasterxml.jackson.databind.JsonNode rootNode = mapper.readTree(jsonstr);		
    	String username =uentity.getUsername();
		try{
			userentity = hasMatchCount(username);
		}catch(EmptyResultDataAccessException er){
			resjson.put("status", "0");
			resjson.put("desc", "找不到用户!");
			return mapper.writeValueAsString(resjson);
		}
		Date date = new Date();
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setRname("用户管理/修改密码");
		ulog.setCreateusername(uentity.getUsername());
		ulog.setUserid(uentity.getId());
		ulog.setOrgid(uentity.getOrg_id());
		ulog.setMethod("updatepsw");
		XinLongUtil.xinLongUtil.printlog(log,"获取密码并验证...");
		if(userentity.getPassword().equals(rootNode.get("oldpassword").asText())){
			userentity.setPassword(rootNode.get("password").asText());
			userentity.setNeedpwdchange(0);		
			
			userentity.setUpdatepswtime(dateFormat.format(date));
			try{
				userDao.updateuser(userentity);
				session.setAttribute("USER_SESSION",userentity);
				resjson.put("status", "1");
				resjson.put("desc", "修改成功!");
				ulog.setProceed("操作成功");
				XinLongUtil.saveUserLog(ulog);
			}catch(Exception ex){
				resjson.put("status", "0");
				resjson.put("desc", "升级密码异常!");
				log.error(ex.getMessage());
			}
			
			
		}else{
			resjson.put("status", "0");
			resjson.put("desc", "密码不正确!");
			ulog.setDescriptor("密码不正确!");
			ulog.setProceed("操作失败");
			XinLongUtil.saveUserLog(ulog);
		}
    	return mapper.writeValueAsString(resjson); 
    }
    
    public void C_updateuser(DeferredResult<String> deferredResult,String jsonstr, HttpServletRequest request, HttpSession session) throws JsonProcessingException{  
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	XinLongUtil.xinLongUtil.printlog(log,jsonstr);
    	String remoteaddr = XinLongUtil.getRemoteAddr(request);
    	ObjectMapper mapper = new ObjectMapper(); 
    	ObjectNode resjson = mapper.createObjectNode();
    	com.fasterxml.jackson.databind.JsonNode rootNode;
    	String username = "";
    	String phone = "";    	
    	String rname = "";
    	String org_id = "";
    	String jobname = "";
    	String realname = "";
    	String idcard = "";
    	String sex = "";
    	String descriptor = "";
    	String ckname = "";
    	String descinfo = "";
    	try{
    		rootNode = mapper.readTree(jsonstr);
    		username =rootNode.get("username").asText();
    		phone =rootNode.get("phone").asText();
			rname = rootNode.get("rname").asText();
			org_id =rootNode.get("org_id").asText();
			jobname =rootNode.get("jobname").asText();
			realname =rootNode.get("realname").asText();
			idcard = rootNode.get("idcard").asText();
			sex = rootNode.get("sex").asText();
			descriptor = rootNode.get("descriptor").asText();
			ckname = rootNode.get("ckname").asText();
    	}catch (IOException e1) {
    		resjson.put("status", "2");
    		resjson.put("desc", "解析上传数据异常!");
    		log.error(e1.getMessage());
    		deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}	
    	Date date = new Date();
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	String curname = sentity.getUsername();
    	UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setRname("用户管理/用户编辑");
		ulog.setCreateusername(sentity.getUsername());
		ulog.setUserid(sentity.getId());
		ulog.setOrgid(sentity.getOrg_id());
		ulog.setMethod("updateuser");
    	try{
    		UserEntity uentity = userDao.findByUserName(username);    
    		if(uentity == null) {
    			resjson.put("status", "0");
    			resjson.put("desc", "未找到用户[" + uentity.getRealName() + "]!");
    			deferredResult.setResult(mapper.writeValueAsString(resjson));
    			return;
    		}
    		XinLongUtil.xinLongUtil.printlog(log,"升级用户:"+uentity.getUsername());

    		if(!org_id.equals(uentity.getOrg_id())) {
    			//人员变更机构,名下锁具和钥匙需先移交
    			if(lockDao.findLocksByUser(uentity.getUsername()).size() > 0) {
    				resjson.put("status", "0");
        			resjson.put("desc", "[" + uentity.getRealName() + "]名下还有锁具,请先移交!");
        			deferredResult.setResult(mapper.writeValueAsString(resjson));
        			return;
    			}
    			//判断名下是否有钥匙
    			if(lockDao.findKeysByUserCount("", uentity.getUsername()) > 0) {
    				resjson.put("status", "0");
        			resjson.put("desc", "[" + uentity.getRealName() + "]名下还有钥匙,请先移交!");
        			deferredResult.setResult(mapper.writeValueAsString(resjson));
        			return;
    			}
    		}
    		//判断用户姓名有无改动
    		if(!uentity.getRealName().equals(realname)) {
    			//修改该用户锁具及任务相关信息
    			if(userDao.updatelockuser_realname(username, uentity.getRealName(), realname) == -1) {
    				resjson.put("status", "0");
        			resjson.put("desc", "更新[" + uentity.getRealName() + "]名下锁具信息失败!");
        			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        			deferredResult.setResult(mapper.writeValueAsString(resjson));
        			return;
    			}
    			
    			if(userDao.updatelockmission_realname(username, uentity.getRealName(), realname) == -1) {
    				resjson.put("status", "0");
        			resjson.put("desc", "更新[" + uentity.getRealName() + "]名下任务信息失败!");
        			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        			deferredResult.setResult(mapper.writeValueAsString(resjson));
        			return;
    			}
    			
    			if(userDao.updatelockmissiondetail_realname(username, uentity.getRealName(), realname) == -1) {
    				resjson.put("status", "0");
        			resjson.put("desc", "更新[" + uentity.getRealName() + "]名下任务详情信息失败!");
        			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        			deferredResult.setResult(mapper.writeValueAsString(resjson));
        			return;
    			}
    			
    			descinfo = "[用户姓名由" + uentity.getRealName() + "更改为" + realname + "]";
    		}
    		ulog.setCreate_check_userid(ckname);
			uentity.setAuthtype(0);
			uentity.setCreatename(curname);
			uentity.setDescriptor(descriptor);
			uentity.setIdcard(idcard);
			uentity.setJobname(jobname);
			uentity.setOrg_id(org_id);
			uentity.setPhone(phone);
			uentity.setRealName(realname);
			uentity.setSex(sex);
    		
    		uentity.setUpdatetime(dateFormat.format(date));
    		if(userDao.updateuser(uentity) == 0){
    			resjson.put("status", "0");
    			resjson.put("desc", "更新用户信息失败!");
    			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    			deferredResult.setResult(mapper.writeValueAsString(resjson));
    			return;
    		}
    		//添加用户管理日志
    		if(insertUserOperLog(remoteaddr,uentity.getUsername(),sentity.getUsername(),rname,ckname,sentity.getOrg_id()) == 0){
    			resjson.put("status", "0");
    			resjson.put("desc", "添加日志失败!");
    			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    			deferredResult.setResult(mapper.writeValueAsString(resjson));
    			return;
    		}else{
    			resjson.put("status", "1");
    			resjson.put("desc", "成功!");
    			ulog.setDescriptor(username + "被编辑!" + descinfo);
    			ulog.setProceed("操作成功");
    			XinLongUtil.saveUserLog(ulog);
    		}
    		
    	}catch(EmptyResultDataAccessException er){
    		resjson.put("status", "0");
			resjson.put("desc", "找不到该用户!");
    	}catch(Exception e){
    		resjson.put("status", "2");
			resjson.put("desc", "未知异常!");
			ulog.setDescriptor(e.getMessage());
			ulog.setProceed("操作失败");
			XinLongUtil.saveUserLog(ulog);
			log.error(e.getMessage());
    	}
    	deferredResult.setResult(mapper.writeValueAsString(resjson));
		return;
    }
    
    public int updatetryno(UserEntity uentity){  
    	return userDao.updatetryno(uentity);
    }
    
    public void C_updateUserRole(DeferredResult<String> deferredResult,String jsonstr, HttpServletRequest request, HttpSession session) throws JsonProcessingException{
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	XinLongUtil.xinLongUtil.printlog(log,jsonstr);
    	String remoteaddr = XinLongUtil.getRemoteAddr(request);
    	ObjectMapper mapper = new ObjectMapper();  
		ObjectNode res = mapper.createObjectNode();
		Date date = new Date();
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String userid = "";
		String username = "";
		String roleid = "";
		String rname = "";
		String ckname = "";
		com.fasterxml.jackson.databind.JsonNode rootNode;
		try {
			rootNode = mapper.readTree(jsonstr);
			userid =rootNode.get("userid").asText();
			username =rootNode.get("username").asText();
			roleid =rootNode.get("roleid").asText();
			rname =rootNode.get("rname").asText();
			ckname =rootNode.get("ckname").asText();
		} catch (IOException e1) {
			res.put("status", "2");
			res.put("desc", "解析上传数据异常!");
			deferredResult.setResult(mapper.writeValueAsString(res));
			return;
		}	
    	if(userid.equals(sentity.getId())){
    		res.put("status", "0");
    		res.put("desc", "不能配置自己!");
    		deferredResult.setResult(mapper.writeValueAsString(res));
    		return;
		}
		//权限判断
    	/*res = XinLongUtil.OptAuth(userid,jsonstr, sentity);
		if(!res.get("status").asText().equals("1210")){
			deferredResult.setResult(mapper.writeValueAsString(resjson));
			return;
		}*/
		UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setRname(rname);
		ulog.setCreateusername(sentity.getUsername());
		ulog.setUserid(sentity.getId());
		ulog.setCreate_check_userid(ckname);
		ulog.setMethod("updateUserRole");
		ulog.setOrgid(sentity.getOrg_id());
		try{
			UserRoleEntity userRole = userroleDao.findByUserId(userid);
			if(userRole != null){
				userRole.setRole_id(roleid);			
	    		userRole.setUpdatetime(dateFormat.format(date));
	    		userRole.setUpdatename(sentity.getUsername());
	    		XinLongUtil.xinLongUtil.printlog(log,"开始更新用户权限...");
				int result = userroleDao.updateuserRole(userRole);
	    		if(result == 0){
	    			res.put("status", "0");
	    			res.put("desc", "操作失败,数据库更新异常!");
	    		}else{
	    			//添加用户管理日志
	        		if(insertUserOperLog(remoteaddr,username,sentity.getUsername(),rname,ckname,sentity.getOrg_id()) == 0){
	        			res.put("status", "0");
	        			res.put("desc", "添加日志失败!");
	        			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	        			deferredResult.setResult(mapper.writeValueAsString(res));
	        			return;
	        		}else{
	        			res.put("status", "1");
	        			res.put("desc", "成功!");
	        			ulog.setDescriptor("更新用户角色");
	        			ulog.setProceed("操作成功");
	        			XinLongUtil.saveUserLog(ulog);
	        		} 
	    		}
			}else{
				//第一次指定用户角色
				XinLongUtil.xinLongUtil.printlog(log,"第一次指定用户角色.....");
	    		userRole = new UserRoleEntity();
	    		userRole.setCreatename(sentity.getUsername());
	    		userRole.setRole_id(roleid);
	    		userRole.setUser_id(userid);
	    		userRole.setCreatetime(dateFormat.format(date));
	    		if(userroleDao.saveuser(userRole) == 1){
	    			//更新用户状态
	    			if(userDao.updateStatus(0, userid) == 1){
	    				//添加用户管理日志
		        		if(insertUserOperLog(remoteaddr,username,sentity.getUsername(),rname,ckname,sentity.getOrg_id()) == 0){
		        			res.put("status", "0");
		        			res.put("desc", "添加日志失败!");
		        			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		        			deferredResult.setResult(mapper.writeValueAsString(res));
		        			return;
		        		}else{
		        			res.put("status", "1");
		        			res.put("desc", "成功!");
		        			ulog.setDescriptor("添加用户角色");
		        			ulog.setProceed("操作成功");
		        			XinLongUtil.saveUserLog(ulog);
		        		} 
	    			}else{
	    				res.put("status", "0");
	        			res.put("desc", "更新用户状态失败!");
	    			}
	    			
	    		}else{
	    			res.put("status", "0");
	    			res.put("desc", "更新失败!");
	    		}
			}   		   		
    	}catch(Exception e){
    		res.put("status", "0");
			res.put("desc", "未知错误!");
			ulog.setDescriptor(e.getMessage());
			ulog.setProceed("操作失败");
			XinLongUtil.saveUserLog(ulog);
			log.error(e.getMessage());
    	}
    	
		deferredResult.setResult(mapper.writeValueAsString(res));
		return;
    }
    
    public void C_resetUserPsw(DeferredResult<String> deferredResult,String jsonstr, HttpServletRequest request, HttpSession session) throws JsonProcessingException{
    	UserEntity uentity = (UserEntity)session.getAttribute("USER_SESSION");
    	XinLongUtil.xinLongUtil.printlog(log,jsonstr);
    	ObjectMapper mapper = new ObjectMapper();  
    	String remoteaddr = XinLongUtil.getRemoteAddr(request);
		ObjectNode res = mapper.createObjectNode();
		Date date = new Date();
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setCreateusername(uentity.getUsername());
		ulog.setUserid(uentity.getId());
		ulog.setMethod("resetUserPsw");
		ulog.setOrgid(uentity.getOrg_id());
		try{
			com.fasterxml.jackson.databind.JsonNode rootNode = mapper.readTree(jsonstr);		
			String username =rootNode.get("username").asText();
			String userid =rootNode.get("userid").asText();
			String rname = rootNode.get("rname").asText();
			String ckname = rootNode.get("ckname").asText();
			//排除自己
			XinLongUtil.xinLongUtil.printlog(log,"-----排除自己:"+uentity.getId());
			if(userid.equals(uentity.getId())){
	    		res.put("status", "0");
	    		res.put("desc", "不能配置自己!");
	    		deferredResult.setResult(mapper.writeValueAsString(res));
	    		return;
			}
			//权限判断
			/*res = XinLongUtil.OptAuth(userid,jsonstr, uentity);
			if(!res.get("status").asText().equals("1210")){
				deferredResult.setResult(mapper.writeValueAsString(res));
				return;
			}*/
			
			ulog.setRname(rname);			
			ulog.setCreate_check_userid(ckname);
			int needup = XinLongUtil.xinLongUtil.isNeedChangePsw();
    		int result = userDao.resetpwd(username, defaultpsw,needup);
    		if(result == 0){
    			res.put("status", "0");
    			res.put("desc", "找不到该用户!");
    		}else{
    			//添加用户管理日志
        		if(insertUserOperLog(remoteaddr,username,uentity.getUsername(),rname,ckname,uentity.getOrg_id()) == 0){
        			res.put("status", "0");
        			res.put("desc", "添加日志失败!");
        			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        			deferredResult.setResult(mapper.writeValueAsString(res));
        			return;
        		}else{
        			res.put("status", "1");
        			res.put("desc", "成功!");
        			ulog.setDescriptor(username + "被重置密码");
        			ulog.setProceed("操作成功");
        			XinLongUtil.saveUserLog(ulog);
        		} 
    		}
    		   		
    	}catch(EmptyResultDataAccessException er){           	
    		res.put("status", "0");
			res.put("desc", "找不到该用户!");
    	}catch(Exception e){
    		res.put("status", "0");
			res.put("desc", "未知错误!");
			ulog.setDescriptor(e.getMessage());
			ulog.setProceed("操作失败");
			XinLongUtil.saveUserLog(ulog);
			log.error(e.getMessage());
    	}
    	
		deferredResult.setResult(mapper.writeValueAsString(res));
		return;
    }
    
    public void C_unlockUser(DeferredResult<String> deferredResult,String jsonstr, HttpServletRequest request, HttpSession session) throws JsonProcessingException{
    	XinLongUtil.xinLongUtil.printlog(log,jsonstr);
    	UserEntity uentity = (UserEntity)session.getAttribute("USER_SESSION");
    	ObjectMapper mapper = new ObjectMapper();  
    	String remoteaddr = XinLongUtil.getRemoteAddr(request);
		ObjectNode res = mapper.createObjectNode();
		try{
			com.fasterxml.jackson.databind.JsonNode rootNode = mapper.readTree(jsonstr);		
			String rname =rootNode.get("rname").asText();
			String id =rootNode.get("userid").asText();
			String username =rootNode.get("username").asText();
			String ckname = rootNode.get("ckname").asText();
			int result = 0;
			//权限判断
			/*res = XinLongUtil.OptAuth(id,jsonstr, uentity);
			if(!res.get("status").asText().equals("1210")){
				deferredResult.setResult(mapper.writeValueAsString(res));
	    		return;
			}*/
			Date date = new Date();
			SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			UserLogEntity ulog = new UserLogEntity();
			ulog.setId(UUID.randomUUID().toString().replace("-", ""));
			ulog.setRemote_addr(remoteaddr);
			ulog.setCreatetime(dateFormat.format(date));
			ulog.setArgs_json(jsonstr);
			ulog.setRname(rname);
			ulog.setCreateusername(uentity.getUsername());
			ulog.setUserid(uentity.getId());
			ulog.setCreate_check_userid(ckname);
			ulog.setMethod("unlockUser");
			ulog.setOrgid(uentity.getOrg_id());
			UserRoleEntity usr = userroleDao.findByUserId(id);
			//判断用户是否已指定角色
			
			if(usr != null){
				result = userDao.updateStatus(0, id);
			}else{
				result = userDao.updateStatus(2, id);
			}

    		
    		if(result == 0){
    			res.put("status", "0");
    			res.put("desc", "找不到该用户!");
    		}else{
    			//添加用户管理日志
        		if(insertUserOperLog(remoteaddr,username,uentity.getUsername(),rname,ckname,uentity.getOrg_id()) == 0){
        			res.put("status", "0");
        			res.put("desc", "添加日志失败!");
        			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        			deferredResult.setResult(mapper.writeValueAsString(res));
    	    		return;
        		}else{
        			res.put("status", "1");
        			res.put("desc", "成功!");
        			ulog.setDescriptor("用户被解锁");
        			ulog.setProceed("操作成功");
        			XinLongUtil.saveUserLog(ulog);
        		} 
    		}
    		   		
    	}catch(EmptyResultDataAccessException er){           	
    		res.put("status", "0");
			res.put("desc", "找不到该用户!");
    	}catch(Exception e){
    		res.put("status", "0");
			res.put("desc", "未知错误!");
			log.error(e.getMessage());
    	}
    	
		deferredResult.setResult(mapper.writeValueAsString(res));
		return;
    }
    
    public void C_lockUser(DeferredResult<String> deferredResult,String jsonstr, HttpServletRequest request, HttpSession session) throws JsonProcessingException{
    	XinLongUtil.xinLongUtil.printlog(log,jsonstr);
    	UserEntity uentity = (UserEntity)session.getAttribute("USER_SESSION");
    	ObjectMapper mapper = new ObjectMapper();  
		ObjectNode res = mapper.createObjectNode();
		String remoteaddr = XinLongUtil.getRemoteAddr(request);
		try{
			com.fasterxml.jackson.databind.JsonNode rootNode = mapper.readTree(jsonstr);		
			String userid =rootNode.get("userid").asText();
			String username =rootNode.get("username").asText();
			String rname =rootNode.get("rname").asText();
			String ckname = rootNode.get("ckname").asText();
			/*res = XinLongUtil.OptAuth(userid,jsonstr, uentity);
			if(!res.get("status").asText().equals("1210")){
				deferredResult.setResult(mapper.writeValueAsString(res));
	    		return;
			}*/
			Date date = new Date();
			SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			UserLogEntity ulog = new UserLogEntity();
			ulog.setId(UUID.randomUUID().toString().replace("-", ""));
			ulog.setRemote_addr(remoteaddr);
			ulog.setCreatetime(dateFormat.format(date));
			ulog.setArgs_json(jsonstr);
			ulog.setRname(rname);
			ulog.setCreateusername(uentity.getUsername());
			ulog.setUserid(uentity.getId());
			ulog.setCreate_check_userid(ckname);
			ulog.setMethod("lockUser");
			ulog.setOrgid(uentity.getOrg_id());
    		int result = userDao.updateStatus(1, userid);
    		if(result == 0){
    			res.put("status", "0");
    			res.put("desc", "找不到该用户!");
    		}else{
    			//添加用户管理日志
        		if(insertUserOperLog(remoteaddr,username,uentity.getUsername(),rname,ckname,uentity.getOrg_id()) == 0){
        			res.put("status", "0");
        			res.put("desc", "添加日志失败!");
        			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        			deferredResult.setResult(mapper.writeValueAsString(res));
    	    		return;
        		}else{
        			res.put("status", "1");
        			res.put("desc", "成功!");
        			ulog.setDescriptor("用户被锁定");
        			ulog.setProceed("操作成功");
        			XinLongUtil.saveUserLog(ulog);
        		} 
    		}
    		   		
    	}catch(EmptyResultDataAccessException er){           	
    		res.put("status", "0");
			res.put("desc", "找不到该用户!");
    	}catch(Exception e){
    		res.put("status", "0");
			res.put("desc", "未知错误!");
			log.error(e.getMessage());
    	}
    	
		deferredResult.setResult(mapper.writeValueAsString(res));
		return;
    }    
    
    public void getUserNamelist(DeferredResult<String> deferredResult,String jsonstr, HttpServletRequest request, HttpSession session) throws JsonProcessingException{
    	XinLongUtil.xinLongUtil.printlog(log,jsonstr);
    	ObjectMapper mapper = new ObjectMapper();  
		ObjectNode res = mapper.createObjectNode();
		ArrayNode rootnode = mapper.createArrayNode();
		String orgid = "";
		com.fasterxml.jackson.databind.JsonNode rootNode;
		try {
			rootNode = mapper.readTree(jsonstr);
			orgid =rootNode.get("orgid").asText();
		} catch (IOException e1) {
			res.put("status", "2");
			res.put("desc", "解析上传数据异常!");
			deferredResult.setResult(mapper.writeValueAsString(res));
			return;
		}	
		List<OrganizationEntity> suborgs = userDao.findSubOrg(orgid);
		List<UserRoleUnionOrg> urolist = null;
		urolist =userDao.findSubUsers(suborgs);
		ObjectNode tjson = null;
    	for(UserRoleUnionOrg user : urolist) {
    		tjson = mapper.createObjectNode();
			tjson.put("username", user.getUsername());
			tjson.put("realname", user.getRealname());			
			rootnode.add(tjson);
    	}
    	res.put("status", "1");
    	res.put("datas", rootnode);
		deferredResult.setResult(mapper.writeValueAsString(res));
		return;
    }
    
    public void getUserNamelist2(DeferredResult<String> deferredResult,String jsonstr, HttpServletRequest request, HttpSession session) throws JsonProcessingException{
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	ObjectMapper mapper = new ObjectMapper();  
		ObjectNode res = mapper.createObjectNode();
		ArrayNode rootnode = mapper.createArrayNode();
		String orgid = "";
		int mtype = 0;
		com.fasterxml.jackson.databind.JsonNode rootNode;
		try {
			rootNode = mapper.readTree(jsonstr);
			orgid =rootNode.get("orgid").asText();
			mtype =rootNode.get("mtype").asInt();
		} catch (IOException e1) {
			res.put("status", "2");
			res.put("desc", "解析上传数据异常!");
			deferredResult.setResult(mapper.writeValueAsString(res));
			return;
		}	
		List<UserRoleUnionOrg> urolist = null;
		if(mtype != 2) {
			if(orgid.equals("")) {
				List<OrganizationEntity> suborgs = null;
				if(userDao.isRootOrg(sentity.getOrg_id())) {
					urolist =userDao.findSubUsers();
				}else {
					suborgs = userDao.findSubOrg(sentity.getOrg_id());
					urolist =userDao.findSubUsers(suborgs);
				}
				
				try{    		
		        	if(urolist !=null && urolist.size() > 0){
		        		//赋值角色
		        		for(UserRoleUnionOrg ur : urolist){
		        			RoleEntity role = roleDao.findRolenameByUserId(ur.getId());
		        			if(role != null){
		        				ur.setRoleid(role.getId());
		            			ur.setRolename(role.getRolename());
		        			}        			
		        		}
		        	}
		    	}catch(Exception e){
		    		log.error(e.getMessage());
		    	}
			}else {
				urolist =userDao.findUsersByOrgid(orgid);
				try{    		
		        	if(urolist !=null && urolist.size() > 0){
		        		//赋值角色
		        		for(UserRoleUnionOrg ur : urolist){
		        			RoleEntity role = roleDao.findRolenameByUserId(ur.getId());
		        			if(role != null){
		        				ur.setRoleid(role.getId());
		            			ur.setRolename(role.getRolename());
		        			}        			
		        		}
		        	}
		    	}catch(Exception e){
		    		log.error(e.getMessage());
		    	}
			}
		}else {
			//查找金库角色
			if(orgid.equals("")) {
				List<OrganizationEntity> suborgs = userDao.findSubOrg(sentity.getOrg_id());
				
				urolist =userDao.findSubJinKuUsers(suborgs);

			}else {
				urolist =userDao.findJinKuUsersByOrgid(orgid);
				
			}
		}
		
		
		ObjectNode tjson = null;
    	for(UserRoleUnionOrg user : urolist) {
    		tjson = mapper.createObjectNode();
			tjson.put("username", user.getUsername());
			tjson.put("oper_reals", user.getRealname());
			tjson.put("rolename", user.getRolename());
			tjson.put("roleid", user.getRoleid());
			rootnode.add(tjson);
    	}
    	res.put("status", "1");
    	res.put("datas", rootnode);
		deferredResult.setResult(mapper.writeValueAsString(res));
		return;
    }
    
    public void getUserNamelist3(DeferredResult<String> deferredResult, HttpServletRequest request, HttpSession session) throws JsonProcessingException{
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	ObjectMapper mapper = new ObjectMapper();  
		ObjectNode res = mapper.createObjectNode();
		ArrayNode rootnode = mapper.createArrayNode();
			
		List<UserRoleUnionOrg> urolist = null;
		urolist =userDao.findUsersByOrgid(sentity.getOrg_id());
		try{    		
        	if(urolist !=null && urolist.size() > 0){
        		//赋值角色
        		for(UserRoleUnionOrg ur : urolist){
        			RoleEntity role = roleDao.findRolenameByUserId(ur.getId());
        			if(role != null){
        				ur.setRoleid(role.getId());
            			ur.setRolename(role.getRolename());
        			}        			
        		}
        	}
    	}catch(Exception e){
    		log.error(e.getMessage());
    	}
		
		ObjectNode tjson = null;
    	for(UserRoleUnionOrg user : urolist) {
    		tjson = mapper.createObjectNode();
			tjson.put("username", user.getUsername());
			tjson.put("realname", user.getRealname());
			tjson.put("rolename", user.getRolename());
			rootnode.add(tjson);
    	}
    	res.put("status", "1");
    	res.put("datas", rootnode);
		deferredResult.setResult(mapper.writeValueAsString(res));
		return;
    }
    
    public void _insertfinger(DeferredResult<String> deferredResult,String jsonstr, HttpServletRequest request,HttpSession session) throws JsonProcessingException{  
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	String remoteaddr = XinLongUtil.getRemoteAddr(request);
    	ObjectMapper mapper = new ObjectMapper(); 
    	ObjectNode resjson = mapper.createObjectNode();
    	FingerEntity finger = null;
    	com.fasterxml.jackson.databind.JsonNode rootNode;
    	XinLongUtil.xinLongUtil.printlog(log,jsonstr);
    	String username = "";
    	int fingerflag = 0;    	
    	String rname = "";    	
    	String fingerbase = "";
    	try{
    		rootNode = mapper.readTree(jsonstr);
    		username =rootNode.get("username").asText();
    		fingerbase =rootNode.get("fingerbase").asText();
			rname = rootNode.get("rname").asText();
			fingerflag =rootNode.get("fingerflag").asInt();			
    	}catch (IOException e1) {
    		resjson.put("status", "2");
    		resjson.put("desc", "解析上传数据异常!");
    		log.error(e1.getMessage());
    		deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}	

		Date date = new Date();
		SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		UserLogEntity ulog = new UserLogEntity();
		ulog.setId(UUID.randomUUID().toString().replace("-", ""));
		ulog.setRemote_addr(remoteaddr);
		ulog.setCreatetime(dateFormat.format(date));
		ulog.setArgs_json(jsonstr);
		ulog.setRname("智能锁管理/用户管理/采集指纹");
		ulog.setCreateusername(sentity.getUsername());
		ulog.setUserid(sentity.getId());
		ulog.setCreate_check_userid("");
		ulog.setOrgid(sentity.getOrg_id());
		ulog.setMethod("insertfinger");
		if(userDao.findByUserName(username) == null) {
			resjson.put("status", "2");
    		resjson.put("desc", "找不到指定用户!");
    		deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}
		//查找是否已录入该用户指定手指指纹信息
		finger = userDao.findFingerbase(username, fingerflag);
		if(finger != null) {
			//删除原录入信息
			if(userDao.deletefinger(finger.getUsername(), finger.getFingerflag()) != 1) {
				resjson.put("status", "2");
	    		resjson.put("desc", "删除原指纹信息失败!");
	    		deferredResult.setResult(mapper.writeValueAsString(resjson));
	    		return;
			}
			//删除缓存指纹信息
			ZZFingerUtil.zzFingerUtil.DeluserDetail(username+"-"+fingerflag);
		}
		finger = new FingerEntity();
		String uId = UUID.randomUUID().toString().replace("-", "");
		finger.setId(uId);
		finger.setFingerflag(fingerflag);
		finger.setUsername(username);
		finger.setFingerbase(fingerbase);
		if(userDao.savefinger(finger) != 1) {
			resjson.put("status", "2");
    		resjson.put("desc", "添加指纹信息失败!");
    		deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}
		//在缓存中添加新指纹
		ZZFingerUtil.zzFingerUtil.AdduserFinger(username+"-"+fingerflag, fingerbase);
		resjson.put("status", "1");
		resjson.put("desc", "采集录入成功!");
		ulog.setDescriptor("用户" + username + "录入指纹!");
		ulog.setProceed("操作成功");
		XinLongUtil.saveUserLog(ulog);
		deferredResult.setResult(mapper.writeValueAsString(resjson));
		return;
    }
    
    public void authfinger(DeferredResult<String> deferredResult,String jsonstr, HttpServletRequest request,HttpSession session) throws JsonProcessingException{  
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	String remoteaddr = XinLongUtil.getRemoteAddr(request);
    	ObjectMapper mapper = new ObjectMapper(); 
    	ObjectNode resjson = mapper.createObjectNode();

    	com.fasterxml.jackson.databind.JsonNode rootNode;
    	XinLongUtil.xinLongUtil.printlog(log,jsonstr);
    	String username = "";
    	int fingerflag = 0;    	
    	String rname = "";    	
    	String fingerbase = "";
    	try{
    		rootNode = mapper.readTree(jsonstr);
    		username =rootNode.get("username").asText();
    		fingerbase =rootNode.get("fingerbase").asText();
			rname = rootNode.get("rname").asText();
			fingerflag =rootNode.get("fingerflag").asInt();			
    	}catch (IOException e1) {
    		resjson.put("status", "2");
    		resjson.put("desc", "解析上传数据异常!");
    		log.error(e1.getMessage());
    		deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}	
    	FingerEntity finger = userDao.findFingerbase(username, fingerflag);	
		if(finger == null) {
			resjson.put("status", "2");
    		resjson.put("desc", "找不到指定用户录入的指纹信息!");
    		deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}
		boolean ret = AFISUtil.afisUtil.CompareFinger(AFISUtil.afisUtil.base64String2ByteFun(finger.getFingerbase()), AFISUtil.afisUtil.base64String2ByteFun(fingerbase));
		if(ret) {
			resjson.put("status", "1");
			resjson.put("desc", "验证成功!");
		}else {
			resjson.put("status", "1");
			resjson.put("desc", "验证失败,请重新验证!");
		}
		

		deferredResult.setResult(mapper.writeValueAsString(resjson));
		return;
    }
    
    public void queryfinger(DeferredResult<String> deferredResult,String jsonstr, HttpServletRequest request,HttpSession session) throws JsonProcessingException{  
    	UserEntity sentity = (UserEntity)session.getAttribute("USER_SESSION");
    	String remoteaddr = XinLongUtil.getRemoteAddr(request);
    	ObjectMapper mapper = new ObjectMapper(); 
    	ObjectNode resjson = mapper.createObjectNode();

    	com.fasterxml.jackson.databind.JsonNode rootNode;
    	XinLongUtil.xinLongUtil.printlog(log,jsonstr);
  	
    	String rname = "";    	
    	String fingerbase = "";
    	try{
    		rootNode = mapper.readTree(jsonstr);
    		fingerbase =rootNode.get("fingerbase").asText();
			rname = rootNode.get("rname").asText();		
    	}catch (IOException e1) {
    		resjson.put("status", "2");
    		resjson.put("desc", "解析上传数据异常!");
    		log.error(e1.getMessage());
    		deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
		}	
    	
    	String matched = ZZFingerUtil.zzFingerUtil.find(ZZFingerUtil.zzFingerUtil.base64String2ByteFun(fingerbase));
    	if(matched.equals("")) {
    		resjson.put("status", "2");
    		resjson.put("desc", "无匹配的指纹用户!");
    		deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
    	}else {
    		String[] matches = matched.split("-");
    		resjson.put("status", "1");
    		resjson.put("desc", "匹配到是用户" + matches[0] + "的第" + matches[1] + "枚指纹!");
    		deferredResult.setResult(mapper.writeValueAsString(resjson));
    		return;
    	}
    }
}
